/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tomasio.projects.welcome.dao;


import com.tomasio.projects.welcome.dto.ChaveDTO;
import com.tomasio.projects.welcome.model.Chave;
import com.tomasio.projects.welcome.util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author administrador
 */
public class HibernateChaveDAO implements ChaveDAO {

    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    @Override
    public ChaveDTO find(Long id) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Chave chave = (Chave) session.get(Chave.class, id);
        tx.commit();
        session.close();
        return chave.createDTO();
    }

    @Override
    public void create(ChaveDTO chave) {
        Chave _chave = new Chave(chave);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.save(_chave);
        tx.commit();
        session.close();
    }

    @Override
    public void remove(Long id) {
        ChaveDTO dto = find(id);
        Chave chave = new Chave(dto);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.delete(chave);
        tx.commit();
        session.close();
    }

    @Override
    public void update(ChaveDTO chave) {
        Chave _chave = new Chave(chave);
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.update(_chave);
        tx.commit();
        session.close();
    }

    @Override
    public List<ChaveDTO> findAll() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        List<Chave> cartoes = session.createQuery("from Chave chave order by chave.numero").list();
        tx.commit();
        session.close();

        List<ChaveDTO> dtoList = new ArrayList<ChaveDTO>();
        for (Chave chave : cartoes) {
            dtoList.add(chave.createDTO());
        }
        return dtoList;
    }

    @Override
    public ChaveDTO findByNumero(String numero) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Chave chave = (Chave) session.createQuery("from Chave chave where chave.numero='"
                + numero + "'").uniqueResult();
        tx.commit();
        session.close();
        return chave.createDTO();
    }
}
